package com.sky.interceptor;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.AccountNotFoundException;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangqi
 * @date 2023/12/26 09:03
 */
@Slf4j
@Configuration
public class AdminTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求的url
        StringBuffer url = request.getRequestURL();
        log.info("拦截器拦截到一个请求url:{}",url);

        //2.判断是否是动态资源，如果是动态资源就拦截，否则放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //3.获取token（已登录的令牌）
        String token = request.getHeader("token");

        if(token == null){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_LOGIN);
        }

        //4.如果前面没有执行，就表示有token，接下来解析token
        try {
            Claims claims = JwtUtil.parseJWT("mjxy", token);
            Long empId = Long.valueOf(claims.get("empId").toString());
            log.info("解析token成功，已登录的用户id:{}",empId);
            //把用户的登录的用户id保存起来,ThreadLocal保存
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception e) {
            throw new AccountNotFoundException(MessageConstant.USER_NOT_LOGIN);
        }
    }
}
